$(document).ready(function() {
	/*
	var socket = new WebSocket('ws://localhost:9000/orders?establishmentId=5&beginTime=' + new Date().getTime()+'&endTime=' + new Date().getTime()); 
	
	socket.onmessage = function(evt) {
		console.debug(evt.data);
    }
    */
	
	$('#store-pills > li').click(this, function() {
		initStoreDivs(this);
	});
	
	$("#new_food_court_pill").click(this, function() {
		$('#foodCourtPictureId').attr("src","http://placehold.it/100x100");
		$('#foodCourtNameId').val('')
		$('#foodCourtAddressId').val('')
		$('#foodCourtCityId').val('')
		$('#foodCourtStateId').val('')
		$('#foodCourtZipId').val('')
		$('#foodCourtCountryId').val('')
		$('#foodCourtPhoneId').val('')
		
		// pills activation
		$("#new_food_court_pill").parent().addClass("active");
		$("#new_Store_Pill").parent().removeClass("active");
		
		//hidden the active main div
		$(".div_show").removeClass("div_show").addClass("div_hidden");
		
		//show court div
		$("#food_court_div").removeClass("div_hidden").addClass("div_show");
	});
	
	$("#new_store_pill").click(this, function() {
		initStoreDivs($('#store-basics-pill'));
		$('#storePictureId').attr("src","http://placehold.it/100x100");
		$('#storeNameId').val('')
		$('#storeAddressId').val('')
		$('#storeCityId').val('')
		$('#storeStateId').val('')
		$('#storeZipId').val('')
		$('#storeCountryId').val('')
		$('#storePhoneId').val('')
		
		//hidden the active main div
		$(".div_show").removeClass("div_show").addClass("div_hidden");

		//show court div
		$("#store_div").removeClass("div_hidden").addClass("div_show");
	});
	
	$('#foodCourtSaveButton').click(function () {
		$('#foodCourtFormId').ajaxSubmit({ 
			success:  function (data) {
				$('#foodCourtPictureId').attr("src", data.picture.URL);
			},  // post-submit callback 
			//beforeSend : SpinnerHelper.showSpinner,
			// complete: SpinnerHelper.hideSpinner,
			dataType: 'json',
		    error: function (data) {console.debug(data)},
		    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
		    iframe: true
		});
	});
	
	$('#storeSaveButton').click(function () {
		$('#storeFormId').ajaxSubmit({ 
			success:  function (data) {
				$('#storePictureId').attr("src", data.picture.URL);
			},  // post-submit callback 
			//beforeSend : SpinnerHelper.showSpinner,
			// complete: SpinnerHelper.hideSpinner,
			dataType: 'json',
		    error: function (data) {console.debug(data)},
		    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
		    iframe: true
		});
	});
	
	$(".foodCourtItem").click(this, function () {
		selectFoodCourt(this);
		
		//hidden the active main div
		$(".div_show").removeClass("div_show").addClass("div_hidden");
		
		//show court div
		$("#food_court_div").removeClass("div_hidden");
		$("#food_court_div").addClass("div_show");
		
		var func = Ajax.services['LOAD_PLACE'];
		var foodCourtId = $(this).attr('placeId');
		var url = func({id: foodCourtId});
		
		Ajax.load(url, {}, showFoodCourt, null, 'json', 'GET');
	});
});

function showFoodCourt(data) {
	$('.storeItem').remove();

	$("#foodCourtIdId").val(data.id);
	$("#foodCourtNameId").val(data.name);
	$("#foodCourtAddressId").val(data.address.address);
	$("#foodCourtCityId").val(data.address.city);
	$("#foodCourtStateId").val(data.address.state);
	$("#foodCourtZipId").val(data.address.zip);
	
	if (data.telephones && data.telephones.length != 0) {
		var tds = '';
		
		for ( var i = 0; i < data.telephones.length; i++) {
			var telephone = data.telephones[i];
			tds += '<tr><td>';
			tds += telephone.type;
			tds += '</td><td>';
			tds += telephone.number;
			tds += '</td></tr>';
		}
		$("#foodCourtTelephonesTableId").append(tds);
		$("#foodCourtTelephonesTableId").show();
	}
	if (data.picture) {
		$('#foodCourtPictureId').attr('src', data.picture.URL);
	} else {
		$('#foodCourtPictureId').attr('src', 'http://placehold.it/100x100');
	}
	if (data.establishments && data.establishments.length != 0) {
		for (var i = 0; i < data.establishments.length; i++) {
			var establishment = data.establishments[i];
			$('<li>').attr('storeId', establishment.id).addClass('storeItem').appendTo($("#ulStoreId")).
			append($('<a></a>').text(establishment.name).attr('href', '#')).click(function () {
				$(".storeItem").removeClass('active');
				$(this).addClass('active');
				
				//hidden the active main div
				$(".div_show").removeClass("div_show").addClass("div_hidden");

				//show court div
				$("#store_div").removeClass("div_hidden").addClass("div_show");
				initStoreDivs($('#store-basics-pill'));
				
				var func = Ajax.services['LOAD_PLACE'];
				var url = func({id: $(this).attr('storeId')});
				
				Ajax.load(url, {}, showEstablishment, null, 'json', 'GET');
			});
		}
		
		//VER PQ APENAS UM $("#divStoresId").show() NÃO ESTA FUNCIONANDO. TEM SEMPRE Q REMOVER A CLASSE
		//E ADICIONAR OUTRA
		$("#divStoresId").removeClass("div_hidden");
		$(".storeItem").removeClass('active');
	}
}

function showEstablishment(data) {
	$("#storeIdId").val(data.id);
	$("#storeNameId").val(data.name);
	$("#storeAddressId").val(data.address.address);
	$("#storeCityId").val(data.address.city);
	$("#storeStateId").val(data.address.state);
	$("#storeZipId").val(data.address.zip);
	if(data.telephones.length > 0) {
		$("#storePhoneId").val(data.telephones[0].number);
	} else {
		$("#storePhoneId").val('');
	}
}

function initStoreDivs(pill) {
	$('#store-pills > li').removeClass('active');
	$(pill).addClass('active');
	$('#store_div > .row-fluid > div').hide();
	var divPrefix = $(pill).attr('id');
	console.log(divPrefix);
	$('#' + divPrefix + '-div').show();
}	

function selectFoodCourt(li) {
	$(".foodCourtItem").removeClass('active');
	$(li).addClass('active');
}

var Ajax = {
	services : [],
	
	load : function (url , parameters, successCallback, errorCallback, dataType, method) {
		$.ajax({
			  url: url,
			  /*
			  beforeSend : SpinnerHelper.showSpinner,
			  complete: SpinnerHelper.hideSpinner, */
			  data: parameters,
			  success: successCallback,
			  error: errorCallback ? errorCallback : Ajax.defaultError,
			  dataType: dataType ? dataType : 'html',
			  type: method ? method : 'POST',
			  timeout: 30000 //30 seconds 
			  }
		);
	},
	
	defaultError : function (jqXHR, textStatus, errorThrown) {
	  //textStatus pode ser "timeout", "error", "abort", and "parsererror"
	  //errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."
		//SpinnerHelper.hideSpinner();
		console.debug('jqXHR = ' + jqXHR);
		console.debug('textStatus = ' + textStatus);
		console.debug('errorThrown = ' + errorThrown);
	 }
};